package com.music.service.songs.dao.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Set;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.music.service.jdosupport.PMF;
import com.music.service.songs.beans.Song;
import com.music.service.songs.beans.SongMemberUrl;
import com.music.service.songs.constants.SongState;
import com.music.service.songs.dao.SongDAO;

public class SongJDOImpl implements SongDAO {

	public Song addNewSong(Song pSong) {
		pSong.setSongState(SongState.ACTIVE);
		PersistenceManager persistenceManager = PMF.get()
				.getPersistenceManager();
		try {
			pSong = persistenceManager.makePersistent(pSong);
		} finally {
			persistenceManager.close();
		}
		return pSong;
	}

	public boolean checkMemberPermissionForSong(Long pMemberId, Long pSongId) {
		// TODO Auto-generated method stub
		return false;
	}

	public void deleteSong(Song pSong) {
		pSong.setSongState(SongState.DELETED);
		PersistenceManager persistenceManager = PMF.get()
				.getPersistenceManager();
		try {
			persistenceManager.makePersistent(pSong);
		} finally {
			persistenceManager.close();
		}
	}

	public Song editSong(Song pSong) {
		PersistenceManager persistenceManager = PMF.get()
				.getPersistenceManager();
		try {
			persistenceManager.makePersistent(pSong);
		} finally {
			persistenceManager.close();
		}
		return pSong;
	}

	public boolean setPreferredUrlForSongForMember(Long pMemberId,
			Long pSongId, Long pUrlId) {
		// TODO Auto-generated method stub
		return false;
	}
	
	public List<Long> getUrlsForSongsForMember(Long pMemberId,Set<Long> pSongIds){
		PersistenceManager persistenceManager = PMF.get()
		.getPersistenceManager();

		Query query = persistenceManager.newQuery(SongMemberUrl.class,
			":p.contains(songId)");
		query.setFilter("memberId == memberIdParam");
		query.declareParameters("Long memberIdParam");
		
		List<SongMemberUrl> songs = (List<SongMemberUrl>) query.execute(Arrays.asList(pSongIds),pMemberId);
		List<Long> urls = new ArrayList<Long>();
		
		for(SongMemberUrl smu : songs){
			urls.add(smu.getUrlId());
		}
		return urls;
	}

	@SuppressWarnings("unchecked")
	public List<Song> viewSongs(Collection<Long> pSongIds) {
		if(pSongIds == null || pSongIds.isEmpty()){
			return new ArrayList<Song>(1);
		}
		
		PersistenceManager persistenceManager = PMF.get()
				.getPersistenceManager();

		Query query = persistenceManager.newQuery(Song.class,
				"p.contains(songId)");
		
		List<Song> songs = (List<Song>) query.execute(Arrays.asList(pSongIds));

		return songs;
	}

}
